/***************************************************************************
    begin                : aug 01 2010
    copyright            : (C) 2010 by Benoit Valot
    email                : benvalot@gmail.com
 ***************************************************************************/

/***************************************************************************
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 23 of the License, or     *
 *   (at your option) any later version.                                   *
 *                                                                         *
 ***************************************************************************/

package val.lemonde;

import java.util.ArrayList;

import val.lemonde.FragmentListArticle.OnArticleSelectedListener;
import val.lemonde.FragmentPage.OnLinkSelectedListener;

import com.markupartist.android.widget.ActionBar;

import android.content.Intent;
import android.os.AsyncTask;
import android.os.AsyncTask.Status;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;

public class ActivityPage extends ActivityLemondeBase implements
		OnArticleSelectedListener, OnLinkSelectedListener {
	/** Called when the activity is first created. */

	private String pagedata;

	private get_page_content asyntask;

	private Article article;

	private ArrayList<Article> articles;

	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		Log.d("lemonde", "ActivityPage onCreate");
		articles = this.getIntent().getExtras()
				.getParcelableArrayList("articles");

		setContentView(R.layout.main);

		if (savedInstanceState != null) {
			Log.d("lemonde", "On_create_page_activity_from_old");
			article = savedInstanceState.getParcelable("article");
		} else {
			article = this.getIntent().getExtras().getParcelable("article");
			this.load_content();
		}
		// Chargement des articles si dual-mode et pas déjà instancier
		this.loadArticles();

		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		getMenuInflater().inflate(R.menu.page_menu_top, actionBar.asMenu());
		actionBar.setDisplayShowHomeEnabled(true);
		actionBar.setTitle(article.getTitle());
		actionBar.setDisplayHomeAsUpEnabled(true);

	}

	public void loadArticles() {
		if (!this.isDualMode() || this.articles == null) {
			Log.d("lemonde", "ActivityPage Without FragmentList");
			return;
		}
		Log.d("lemonde", "ActivityPage Load FragmentList");
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentListArticle fragment = (FragmentListArticle) fragmentManager
				.findFragmentByTag("articles");
		if (fragment == null) {
			FragmentTransaction fragmentTransaction = fragmentManager
					.beginTransaction();
			fragment = FragmentListArticle.newInstance(articles);
			fragmentTransaction.replace(R.id.container_little, fragment,
					"articles");
			fragmentTransaction.commit();
		}
	}

	public void onSaveInstanceState(final Bundle b) {
		Log.d("lemonde", "ActivityPage onSaveInstanceState");
		if (this.pagedata != null) {
			b.putString("page_data", this.pagedata);
		}
		b.putParcelable("article", article);
		super.onSaveInstanceState(b);
	}

	public void onRestoreInstanceState(final Bundle b) {
		Log.d("lemonde", "ActivityPage onRestoreInstanceState");
		super.onRestoreInstanceState(b);
		String data = b.getString("page_data");
		if (data != null) {
			this.pagedata = data;
			Log.d("lemonde", "Recuperation du content de la page");
		} else {
			Log.d("lemonde", "Rien a recuperer");
			asyntask = new get_page_content();
			asyntask.execute(article.getLinkUri());
		}
	}
	
	@Override
	protected void onDestroy() {
		Log.d("lemonde", "ActivityPage onDestroy");
		if (asyntask != null && !asyntask.getStatus().equals(Status.FINISHED)) {
			asyntask.cancel(true);
		}
		super.onDestroy();
	}

	public void load_content() {
		//On arrete l'ancien 
		if (asyntask != null && !asyntask.getStatus().equals(Status.FINISHED)) {
			asyntask.cancel(true);
		}
		
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		FragmentLoad fragment = new FragmentLoad();
		fragmentTransaction.replace(R.id.container, fragment);
		fragmentTransaction.commit();

		asyntask = new get_page_content();
		asyntask.execute(article.getLinkUri());
	}

	public void load_data() {
		FragmentManager fragmentManager = getSupportFragmentManager();
		FragmentTransaction fragmentTransaction = fragmentManager
				.beginTransaction();
		FragmentPage fragment = FragmentPage.newInstance(this.pagedata);
		fragmentTransaction.replace(R.id.container, fragment, "page");
		fragmentTransaction.commitAllowingStateLoss();
	}

	public void setPagedata(String data) {
		this.pagedata = data;
	}

	public String getPagedata() {
		return pagedata;
	}

	@Override
	public void OnLinkSelected(Article art) {
		Intent i = new Intent(getApplicationContext(), ActivityPage.class);
		i.putExtra("article", art);
		ActivityPage.this.startActivity(i);
	}

	@Override
	public void OnArticleSelected(Article art, int pos) {
		this.article = art;
		ActionBar actionBar = (ActionBar) findViewById(R.id.actionbar);
		actionBar.setTitle(article.getTitle());
		this.load_content();
	}

	public boolean onCreateOptionsMenu(Menu menu) {
		MenuInflater inflater = getMenuInflater();
		inflater.inflate(R.layout.page_menu, menu);
		return super.onCreateOptionsMenu(menu);
	}

	public boolean onOptionsItemSelected(MenuItem item) {
		// Handle item selection
		switch (item.getItemId()) {
		case R.id.share_item:
			try {
				Intent emailIntent = new Intent(Intent.ACTION_SEND);
				emailIntent
						.putExtra(Intent.EXTRA_TEXT,
								"Un article interessant sur le site lemonde.fr:\n"
										+ article.getTitle()
										+ "\n"
										+ article.getUri());
				emailIntent.setType("text/plain");
				startActivity(Intent.createChooser(emailIntent,
						"Partager cet article"));
			} catch (Exception e) {
				new DialogErreur(this, "Partage de l'article", e).show();
			}
			return true;
		case R.id.actionbar_item_home:
			Log.d("lemonde", "home");
			this.finish();
			return true;
		default:
			return super.onOptionsItemSelected(item);
		}
	}

	private class get_page_content extends AsyncTask<String, Void, String> {
		String data;

		// // can use UI thread here
		protected void onPreExecute() {
		}

		protected void onCancelled() {
			Log.d("lemonde", "On Cancel");
		}

		// automatically done on worker thread (separate from UI thread)
		protected String doInBackground(String... args) {
			try {
				PageLoad page_d = new PageLoad(args[0]);
				data = page_d.getContent();
			} catch (Exception e) {
				String error = e.toString() + "\n" + e.getStackTrace()[0]
						+ "\n" + e.getStackTrace()[1];
				return (error);
			}
			return null;
		}

		protected void onPostExecute(String error) {
			if (error == null) {
				ActivityPage.this.setPagedata(data);
				ActivityPage.this.load_data();
			} else {
				// new erreur_dialog(page.this, "Chargement de la page",
				// error).show();
				ActivityPage.this.erreur_loading(error);
			}
		}
	}

}
